<?php

namespace App\Service\User;

use App\Cache\UserRemarkCache;
use App\Constants\ErrorCode;
use App\Helpers\AliyunUtil;
use App\Helpers\Helper;
use App\Helpers\RedisUtil;
use App\Model\Act\ProfileRewardLog;
use App\Model\CloseFriend;
use App\Model\Message;
use App\Model\User;
use App\Model\UserFollow;
use App\Model\UserProfile;
use App\Model\UserSetting;
use App\Model\UserSocialProfile;
use App\Model\UserVisit;
use App\Service\BaseService;

/**
 * 用户详情页
 */
class UserDetailService extends BaseService
{
    public function handle()
    {
        $userId = $this->getUserId();
        $appid=$this->request->input('appid',0);
        // $user = $this->getUser();
        $profileUserId = $this->request->input('profile_user_id', 0);
        $profileUser = User::getUser($profileUserId);
        if ($profileUser && $profileUser->status == User::STATUS_FREEZE) {
            return $this->setError(ErrorCode::USER_NOT_VALID, '该用户涉嫌违规已被冻结账号！');
        } elseif ($profileUser && $profileUser->status == User::STATUS_CANCELLATTED) {
            return $this->setError(ErrorCode::USER_NOT_VALID, '该用户不存在！');
        }
        $profile = UserProfile::getProfile($profileUserId, false, false);
        $ret = UserProfile::buildProfileDetail($profile);
        //是否关注
        $ret['is_liked'] = UserFollow::check($userId, $profileUserId);
        //粉丝数
        $ret['fans_num'] = UserFollow::getFansNum($profileUserId);
        //是否可以语聊（展示语聊按钮）
        $ret['can_call'] = $this->platform == 1 ? 0 : UserProfile::checkCanCall($ret['role'], $profile->call_permit);
        //是否可以聊天（展示打招呼按钮）
        $ret['can_chat'] = $userId == $profileUserId ? 0 : 1;
        //是否可以视频（展示视频按钮）
        $ret['can_video'] = $this->platform == 1 ? 0 : UserProfile::checkCanVideo($ret['role'], $profile->video_permit);

        $ret['remark'] = $userId != $profileUserId ? (new UserRemarkCache())->getRemark($userId, $profileUserId) : '';

        if ($this->curVersion >= '1.0.0') {
            $video = $profile->video ? json_decode($profile->video, true) : [];
            $ret['video_link'] = $video ? AliyunUtil::VOICE_HOST . $video['link'] : '';
            //收费
            $ret['video_coin_setting'] = intval($ret['video_coin_setting']);
            $ret['coin_setting'] = intval($ret['coin_setting']);
            //头像兼容插入处理
            $this->proccessAvatarAndPoster($ret);
            //是否已经完善资料
            $ret['profile_complete'] = ProfileRewardLog::checkAllComplete($userId, $profile) ? 1 : 0;
        }
        //访客记录
        UserVisit::addRecord($userId, $profileUserId);

        //城市屏蔽
//        if (UserProfile::checkRoleHost($profile->role) && $userId != $profileUserId) {
//            $ret['city'] = '';
//        }
//        $ret['city'] = '';

        //视频，语音呼叫限制
        $this->packCallFunctions($ret, $profileUserId, $userId);
        //主播设置显示
        $this->packHostSetting($ret, $profile);

        //根据show_location显示隐藏city
        if(empty($ret["show_location"])){
            unset($ret['city']);
        }

        //私信价格
        $ret['chat_coin_setting'] = intval($ret['chat_coin_setting']);

        //用户资料
        $socialProfile = UserSocialProfile::getProfile($profileUserId);
//        $socialProfile[] = [
//            'type' => '年龄',
//            'value' => "{$profile->age}岁"
//        ];
        if ($appid == 102){
            $socialProfile[] = [
                'type' => '用户ID',
                'value' => $profile->user_profile_id
            ];
        }

        $ret['social_profile'] = $socialProfile;
        //体力
        $ret['energy'] = UserProfile::getEnergy($profileUserId);
        //日志
        check_dev_env() && log_user_result($userId, $ret);
        return $ret;
    }

    function proccessAvatarAndPoster(&$ret)
    {
        if (!$ret['poster_name'] || $ret['poster_name'][0] == $ret['avatar_name']) return false;
        array_unshift($ret['big_poster'], $ret['avatar']);
    }

    /**
     * 通话限制
     */
    function packCallFunctions(&$ret = [], $profileUserId = 0, $userId)
    {
        // if (!User::checkValidVersion($this->curVersion, $this->appId, [1 => '1.2.2', 2 => '1.2.5'])) return;
        $lockInfo = CloseFriend::checkLock(CloseFriend::getCloseValue($userId, $profileUserId));
        $selfProfile = UserProfile::getProfile($userId);
        if (!$selfProfile || $selfProfile->gender == 1) $lockInfo['voice_call'] = $lockInfo['video_call'] = 0;
        $ret = array_merge($ret, [
            'functions' => [
                ['type' => 'voice_call', 'locked' => $lockInfo['voice_call'], 'tip' => '多增加互动，例如文字聊天和送礼物可以更快提高亲密值~', 'lock_close_value' => CloseFriend::checkFuncValue('voice_call')],
                ['type' => 'video_call', 'locked' => $lockInfo['video_call'], 'tip' => '多增加互动，例如文字聊天和送礼物可以更快提高亲密值~', 'lock_close_value' => CloseFriend::checkFuncValue('video_call')]
            ]
        ]);
    }

    /**
     * 主播设置显示
     */
    function packHostSetting(&$ret = [], $hostProfile = null)
    {
        if (!User::checkValidVersion($this->curVersion, $this->appId, ['1.0.0'])) return;
        $setting = UserSetting::getShowPermit($hostProfile->user_id);
        //是否显示魅力值
        $ret['show_charm'] = $setting['show_charm'];
        //是否显示礼物墙
        $ret['show_gift'] = $setting['show_gift'];
        //是否显示位置
        $ret['show_location'] = $setting['show_location'];
    }
}
